var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();



// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');



app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
// 访问时不需要加static 服务会自动加
app.use(express.static(path.join(__dirname, 'public')));
// app.use(express.static(path.join(__dirname, './uploads')));
// 访问前台静态页面
app.use('/',express.static(path.join(__dirname, 'public/dist')));
// 访问时需要加上static
app.use('/uploads', express.static('uploads'))



var jwt = require('./utils/jwt')
async function checkLogin(req, res, next) {
  // let token = req.headers.token;
  // let result = await jwt.verifyToken(token)
  // console.log(result)
  // if (result.code == 100) {
  //   res.send({
  //     code:401,
  //     msg:'无登录信息'
  //   })
  // }else{
  //   next()
  // }

  if (req.url != '/api/users/login' && req.method != 'GET') {
    console.log(req.method)
    //获取请求头携带的token
    let token = req.headers.token;
    //验证token是否过期
    let result = jwt.verifyToken(token);
    // 如果验证通过就next，否则就返回登陆信息不正确(code == 100就是异常情况)
    if (result.code == 100) {
      res.send({
        code: 401,
        msg: '无登录信息'
      });
    } else {
      next();
    }
  } else {
    next();
  }
}

app.use(checkLogin)

// app.use('/', indexRouter);
app.use('/api/users', usersRouter);
// app.get(/a/,function(req,res){
//     console.log(req)
//     res.send('/a/')
// })



// catch 404 and forward to error handler
app.use(function(req, res, next) {
  // next(createError(404));
  res.send('404 非法访问！')
});
// app.use(function (req, res, next) {
//   var err = new Error('Not Found');
//   err.status = 404;
//   res.render('404 非法访问！', {})
// });
// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
